<template>
  <div
    :class="{
      'form-position-right': !formOptions.config.labelPosition || formOptions.config.labelPosition === 'right'
  }">
    <el-form-item
      v-if="element && element.key && !['title', 'subform', 'linkForm', 'associatedApproval'].includes(element.type)"
      :ref="`formItem-${element.key}`"
      :rules="!isDetail && element.options && element.options.required?[{ required: true,validator: validatorFun, trigger: 'change' }]:[]"
      :label="!element.options.isHideField ? element.name : null"
      :class="itemClass"
      prop="value"
    >
      <div
        v-if="!element.options.isHideField"
        slot="label"
        :title="element.name"
        :class="{
          'grey-label': isDetail,
          'width-require': element.options.required && !isDetail,
        }"
        class="flex-label-name">
        <span class="inner-name">{{ element.name }}</span>
        <tipIcon v-if="element.options.tip" :content="element.options.tip" :style="!showMobilePage?{marginLeft: '4px'}:{verticalAlign: 'middle'}" />
        <span v-if="isDetail">:</span>
      </div>
      <FormMakeElement
        v-model="computedValue"
        :is-in-detail="isInDetail"
        :event-data="eventData"
        :is-detail="isDetail"
        :element="element"
        :is-middle="isMiddle"
        :form-options="formOptions"
        :subform-index="subformIndex"
        :subform-element="subformElement"
        is-card-table
        style="max-width: 100%"
        @changeValue="changeValue"
        @changeValueData="changeValueData"
        @clearValidate="clearValidate"
        @handleFormUserSelect="handleFormUserSelect"/>
    </el-form-item>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import FormMakeElement from '../FormMakeElement';
import { mathFormula } from '@/utils/formMakeUtils';
import { initMathFormulaFunction } from '@/utils/formulaMath.js';

export default {
  name: 'FormMakeItem',
  components: {
    FormMakeElement
  },
  model: {
    prop: 'value',
    event: 'changeValue'
  },
  props: {
    element: {
      type: Object,
      default: null
    },
    isMiddle: {
      type: Boolean,
      default: false
    },
    isDetail: { // 是否详情页展示
      type: Boolean,
      default: false
    },
    isInDetail: { // 是否详情页展示，isDetail可能因为事件而改变，导致实际在详情页而 isDetail 为false，这个属性不会改变，详情页永远为true
      type: Boolean,
      default: false
    },
    eventData: { // 事件
      type: Object,
      default: null
    },
    formOptions: {
      type: Object,
      default: () => ({})
    },
    subformIndex: {
      type: Number,
      default: 0
    },
    subformElement: {
      type: Object,
      default: () => ({})
    },
    valueIndex: {
      type: Number,
      default: 0
    },
    parentElement: {
      type: Object,
      default: null
    }
  },
  data() {
    const validatorFun = () => {
      return (rule, value, callback) => {
        const element = this.element;
        const isDisabled = element.options ? element.options.disabled : false;
        const data = this.computedValue;
        const msg = `${element.name}为必填`;
        const arrVal = Array.isArray(data) && data.length === 0;
        if (!isDisabled && !data && data !== 0 || arrVal || JSON.stringify(data) === '{}') {
          callback(new Error(msg));
        } else {
          callback();
        }
      };
    };
    return {
      validatorFun: validatorFun(),
      inInit: true
    };
  },
  computed: {
    ...mapState({
      'selectWidget': state => state.formMake.selectWidget,
      'showMobilePage': state => state.app.showMobilePage
    }),
    computedValue: {
      get() {
        return this.parentElement.value[this.valueIndex][this.element.key];
      },
      set(val) {
        this.$set(this.parentElement.value[this.valueIndex], this.element.key, val);
      }
    },
    itemClass() {
      const labelPosition = this.formOptions.config.labelPosition;
      return {
        'mb0': this.isDetail && labelPosition !== 'top',
        'mb10': this.isDetail && labelPosition === 'top',
        'hide-label': this.element.options.isHideField,
        'inline-item': !this.showMobilePage,
        'mobile-item': this.showMobilePage && labelPosition !== 'top',
        'mobile-richEditor': this.element.type === 'richEditor' && this.showMobilePage && !this.isDetail
      };
    }
  },
  watch: {
    'element.value': {
      handler(data, oldData) {
        if (this.element.type === 'subform' || this.element.type === 'linkForm') {
          this.handelChangeValue();
        }
      }
    }
  },
  methods: {
    selectHistory(data) {
      this.$emit('selectHistory', data);
    },
    clearValidate(key) {
      if (this.$refs[`formItem-${key}`]) {
        this.$refs[`formItem-${key}`].clearValidate();
      }
    },
    handleFormUserSelect(data) {
      this.$emit('handleFormUserSelect', data);
    },
    // 子表单或关联表单新增或删除
    handelChangeValue() {
      const element = this.element;
      setTimeout(() => {
        this.$nextTick(() => {
          mathFormula(this.formOptions, element);
          this.changeValueData(element);
        });
      }, 10);
      setTimeout(() => {
        this.$nextTick(() => {
          initMathFormulaFunction(this.formOptions, element);
        });
      }, 10);
    },
    changeValue(element) {
      this.$emit('changeValue', element);
    },
    changeValueData(element) {
      this.$emit('changeValueData', element);
    }
  }
};
</script>
<style lang="scss" scoped>
.widget-view {
  padding: 10px 0;
  position: relative;
  // border: 1px dashed rgba(170,170,170,.7);
  background-color: #fff;
  margin: 0px;
  &:hover {
    background-color: #EFF3FB;
  }
  &.active {
    background-color: #EFF3FB;
  }
  .form-mask {
    position: absolute;
    left: 0;
    top: 0;
    z-index: 2;
    height: 100%;
    width: 100%;
  }
  &.cursor {
    cursor: pointer;
  }
  &::v-deep {
    .el-form-item {
      margin-bottom: 0;
    }

  }
  .widget-view-action{
    position: absolute;
    right: 28px;
    top: 12px;
    height: 28px;
    line-height: 28px;
    z-index: 9;
    display: flex;
    .icon {
      margin-left: 12px;
      width: 20px;
      height: 20px;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
    }
    &.bottom {
      bottom: 12px;
      top: auto;
    }
    .font13 { font-size: 13px; }
    .font14 { font-size: 14px !important; }
  }
}
.grey-label {
  color: #999;
}
.title-container {
  white-space: nowrap;
  margin-right: 20px;
  margin-top: 8px;
}
.mb10 {
  margin-bottom: 10px;
}
.mt10 {
  margin-top: 10px;
}
.mb0 {
  margin-bottom: 0;
}
.hide-label {
  &::v-deep {
    .el-form-item__content {
      margin-left: 0 !important;
    }
  }
}
.form-position-right {
  &::v-deep {
    .inline-item{
      .el-form-item__label {
        justify-content: flex-end;
      }
    }
  }
}
.inline-item {
  .inner-name {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  .flex-label-name {
    display: flex;
    align-items: center;
    max-width: 100%;
    &.width-require {
      max-width: calc(100% - 11px);
    }
  }
  &::v-deep {
    .el-form-item__label {
      display: flex;
      align-items: center;
    }
  }
}
.mobile-item {
  display: flex;
  align-items: center;
  &::v-deep {
    .el-form-item__label {
      display: flex;
      line-height: 1 !important;
    }
    .el-form-item__content {
      flex: 1;
      margin: 0 !important;
    }
  }
}
.mobile-richEditor {
  flex-wrap: wrap;
    &::v-deep {
    .el-form-item__label {
      width: 100% !important;
      margin: 12px 0;
    }
    .el-form-item__content {
      width: 100%;
      flex: none;
    }
    .textbus-container {
      height: auto !important;
    }
    .textbus-ui-workbench {
      min-height: 200px !important;
    }
  }
}
</style>
